package sk.patt.eshop.data.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.transaction.annotation.Transactional;

import sk.patt.eshop.data.dao.interfaces.CategoryDao;
import sk.patt.eshop.data.dataobjects.Category;

public class CategoryDaoJPAImp extends AbstractDaoJPAImpl<Category> implements CategoryDao {

	public CategoryDaoJPAImp() {
		super(Category.class);
	}

	@Transactional
	public List<Category> findAll() {
		return getJpaTemplate().execute(new JpaCallback<List<Category>>() {
			public List<Category> doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Category> query = em.createQuery("select c from Category c", Category.class);
				return query.getResultList();
			}
		});
	}

	@Transactional
	public int countAll() {
		return getJpaTemplate().execute(new JpaCallback<Integer>() {

			public Integer doInJpa(EntityManager em) throws PersistenceException {
				TypedQuery<Long> query = em.createQuery("select count (c) from Category c", Long.class);
				return (query.getSingleResult()).intValue();
			}
		});
	}

}
